package roman.mosiienko.yalantistestrm;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import roman.mosiienko.yalantistestrm.adapters.MyAdapter;
import roman.mosiienko.yalantistestrm.fragments.MainFragment;
import roman.mosiienko.yalantistestrm.mymodels.Element;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	private  static ArrayList<Element> elements = new ArrayList<Element>();
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private MyAdapter adap;
	private ProgressDialog pd;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_all));
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		pd = ProgressDialog.show(MainActivity.this, "Working...",
				"Collect information", true, false);
		
		ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo nInfo = cm.getActiveNetworkInfo();
	    if (nInfo != null && nInfo.isConnected()) {
	    	new DownloadInfo().execute();
	    }
	    else {

			Toast.makeText(this, "Network error", Toast.LENGTH_SHORT).show();
			pd.dismiss();
	    }
	
		 
	
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
			
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		if (savedInstanceState == null) {
			selectItem(0);
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return false;

	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	private void selectItem(int position) {
		Fragment fragment = new MainFragment(this);
		Bundle args = new Bundle();
		MainFragment.Number = position;
		args.putInt(MainFragment.getID, position);
		fragment.setArguments(args);
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment).commit();
		mDrawerList.setItemChecked(position, true);
		mDrawerLayout.closeDrawer(mDrawerList);
	}


	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	public void onClick(View v) {
		pd = ProgressDialog.show(MainActivity.this, "Working...",
				"Collect information", true, false);
		new DownloadInfo().execute();
		mDrawerList.setAdapter(adap);

	}

	private class DownloadInfo extends
			AsyncTask<String, Void, ArrayList<Element>> {
		protected ArrayList<Element> doInBackground(String... urls) {
			ObjectMapper mapper = new ObjectMapper();
			String listAddr = "http://apitest.yalantis.com/test/";
			try {
				JsonNode root = mapper.readTree(new URL(listAddr).openStream());
				JsonNode elementsNode = root.findValue("items");
				List<LinkedHashMap<String, String>> elements = mapper
						.readValue(elementsNode, List.class);
				ArrayList<Element> elementsArray = new ArrayList<Element>();
				ArrayList<String> temp2;
				for (int i = 0; i < elements.size(); i++) {
					temp2 = new ArrayList<String>(elements.get(i).values());
					elementsArray.add(new Element(temp2));
				}
				return elementsArray;

			} catch (JsonGenerationException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(ArrayList<Element> tempElements) {
			elements.addAll(tempElements);
			adap = new MyAdapter(MainActivity.this, elements);
			mDrawerList.setAdapter(adap);
			pd.dismiss();
		}
	}


}